<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\AliPayAppController;
use App\Http\Controllers\AliPayController;
use App\Http\Controllers\PaymentController;
use App\Models\BrowserProduct;
use App\Models\CollArea;
use App\Models\CollectionProduct;
use App\Models\Product;
use App\Models\ProductCart;
use App\Models\ProductCategory;
use App\Models\ProductList;
use App\Models\ProductOrder;
use App\Models\ProductSku;
use App\Models\ShippingAddress;
use App\Models\UserRanks;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use DB;

class ProductController extends CommonController
{

    /**
     * 首页产品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSelectedProduts(Request $request)
    {
//        $page = $request->page;
//        $start = ($page - 1) * self::$totalList;

        $field = $request->field;

        if (!in_array($field, ['is_hot', 'is_new'])) {
            return response()->json(['status' => 0, 'msg' => '非法操作！']);
        }

        $list = Product::select('id', 'product_name', 'product_introduct', 'member_price', 'cover_ico', 'sell_num')
            ->where('status', 1)
            ->where($field, 1)
//            ->offset($start)
//            ->limit(8)
            ->orderBy('sort', 'asc')
            ->get();

        if (count($list) > 0) {
            foreach ($list as $v) {
                $v->cover_ico = self::$baseImgUrl . '/' . $v->cover_ico;

//                $sku = ProductSku::where('product_id', $v->id)->orderBy('member_price', 'asc')->first();
//                if ($sku) {
//                    $member_price = $sku->member_price;
////                    $parameter = $sku->value;
////                    $parameterId = $sku->id;
//                } else {
//                    $member_price = 0.00;
////                    $parameter = '无';
////                    $parameterId = 0;
//                }
//
//                $v->member_price = $member_price;
//                $v->parameter = $parameter;
//                $v->parameter_id = $parameterId;
            }
        }

        return response()->json(['status' => 1, 'data' => $list]);
    }

    /**
     * 名企名酒名家
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getProdutsByField(Request $request)
    {
        $page = $request->page;
        if (!$page) {
            $page = 1;
        }
        $start = ($page - 1) * self::$totalList;

        $field = $request->field;
        $keyword = $request->keyword;

        $totalNum = Product::where('status', 1)
            ->where(function ($query) use ($field) {
                if ($field) {
                    $query->where($field, 1);
                }
            })
            ->where(function ($query) use ($keyword) {
                if ($keyword) {
                    $query->where('product_name', 'like', '%' . $keyword . '%');
                }
            })
            ->count();

        $list = Product::select('id', 'product_name', 'member_price', 'cover_ico', 'sell_num')
            ->where('status', 1)
            ->where(function ($query) use ($field) {
                if ($field) {
                    $query->where($field, 1);
                }
            })
            ->where(function ($query) use ($keyword) {
                if ($keyword) {
                    $query->where('product_name', 'like', '%' . $keyword . '%');
                }
            })
            ->offset($start)
            ->limit(self::$totalList)
            ->orderBy('sort', 'asc')
            ->get();

        if (count($list) > 0) {
            foreach ($list as $v) {
                $v->cover_ico = self::$baseImgUrl . '/' . $v->cover_ico;
            }
        }

        return response()->json(['status' => 1, 'data' => ['list' => $list, 'total_num' => $totalNum]]);
    }

    /**
     * 分类页产品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCatesProduts(Request $request)
    {
        $page = $request->page;
        if (!$page) {
            $page = 1;
        }
        $start = ($page - 1) * self::$totalList;

        $cateId = $request->cate_id;
        $from = trim($request->from);
        $sweet_id = trim($request->sweet_id);
        $min_price = trim($request->min_price);
        $max_price = trim($request->max_price);

        if ($min_price > 0 && $max_price > 0 && $max_price < $min_price) {
            return response()->json(['status' => 0, 'msg' => '最高价必须大于最低价']);
        }

        $field = $request->field;
        $order = $request->order;
        if (!$field) {
            $field = 'id';
        }
        if (!$order) {
            $order = 'desc';
        }

        $list = Product::select('id', 'product_name', 'product_introduct', 'cover_ico', 'sell_num', 'member_price')
            ->where('status', 1)
            ->where(function ($query) use ($cateId) {
                # 进行判断
                if ($cateId) {
                    $query->where('category_id', '=', $cateId);
                }
            })
            ->where(function ($query) use ($from) {
                # 进行判断
                if ($from) {
                    $query->where('from', 'like', $from);
                }
            })
            ->where(function ($query) use ($sweet_id) {
                # 进行判断
                if ($sweet_id) {
                    $query->where('sweetness', '=', $sweet_id);
                }
            })
            ->where(function ($query) use ($sweet_id) {
                # 进行判断
                if ($sweet_id) {
                    $query->where('sweetness', '=', $sweet_id);
                }
            })
            ->where(function ($query) use ($min_price) {
                # 进行判断
                if ($min_price) {
                    $query->where('member_price', '>=', $min_price);
                }
            })
            ->where(function ($query) use ($max_price) {
                # 进行判断
                if ($max_price) {
                    $query->where('member_price', '=', $max_price);
                }
            })
            ->offset($start)
            ->limit(self::$totalList)
            ->orderBy($field, $order)
            ->get();

        $totalCount = Product::where('status', 1)
            ->where(function ($query) use ($cateId) {
                # 进行判断
                if ($cateId) {
                    $query->where('category_id', '=', $cateId);
                }
            })
            ->where(function ($query) use ($from) {
                # 进行判断
                if ($from) {
                    $query->where('from', 'like', $from);
                }
            })
            ->where(function ($query) use ($sweet_id) {
                # 进行判断
                if ($sweet_id) {
                    $query->where('sweetness', '=', $sweet_id);
                }
            })
            ->where(function ($query) use ($sweet_id) {
                # 进行判断
                if ($sweet_id) {
                    $query->where('sweetness', '=', $sweet_id);
                }
            })
            ->where(function ($query) use ($min_price) {
                # 进行判断
                if ($min_price) {
                    $query->where('member_price', '>=', $min_price);
                }
            })
            ->where(function ($query) use ($max_price) {
                # 进行判断
                if ($max_price) {
                    $query->where('member_price', '=', $max_price);
                }
            })
            ->count();

        if (count($list) > 0) {
            foreach ($list as $v) {
                $v->cover_ico = self::$baseImgUrl . '/' . $v->cover_ico;
            }
        }

        return response()->json(['status' => 1, 'data' => ['list' => $list, 'totalCount' => $totalCount]]);
    }

    /**
     * 搜索到的商品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function searchResult(Request $request)
    {
        $page = $request->page;
        if (!$page) {
            $page = 1;
        }
        $start = ($page - 1) * self::$totalList;

        $keyword = trim($request->keyword);
        if (!$keyword) {
            return response()->json(['status' => 0, 'msg' => '请输入关键词！']);
        }

        $list = Product::select('id', 'product_name', 'product_introduct', 'cover_ico', 'sell_num', 'member_price')
            ->where('status', 1)
            ->where('product_name', 'like', '%' . $keyword . '%')
            ->offset($start)
            ->limit(self::$totalList)
            ->orderBy('id', 'desc')
            ->get();

        $totalCount = Product::where('status', 1)
            ->where('product_name', 'like', '%' . $keyword . '%')
            ->count();

        if (count($list) > 0) {
            foreach ($list as $v) {
                $v->cover_ico = self::$baseImgUrl . '/' . $v->cover_ico;
            }
        }

        return response()->json(['status' => 1, 'data' => ['list' => $list, 'totalCount' => $totalCount]]);
    }

    /**
     * 获取推荐商品
     * @return \Illuminate\Http\JsonResponse
     */
    public function getRecommedProduts()
    {
        $list = Product::select('id', 'product_name', 'product_introduct', 'cover_ico')
            ->where('status', 1)
            ->where('is_recommend', 1)
            ->orderBy('id', 'desc')
            ->get();

        if (count($list) > 0) {
            foreach ($list as $v) {
                $v->cover_ico = self::$baseImgUrl . '/' . $v->cover_ico;

                $sku = ProductSku::where('product_id', $v->id)->orderBy('member_price', 'asc')->first();
                if ($sku) {
                    $member_price = $sku->member_price;
                    $parameter = $sku->value;
                    $parameterId = $sku->id;
                } else {
                    $member_price = 0.00;
                    $parameter = '无';
                    $parameterId = 0;
                }

                $v->member_price = $member_price;
                $v->parameter = $parameter;
                $v->parameter_id = $parameterId;
            }
        }

        return response()->json(['status' => 1, 'data' => $list]);
    }

    /**
     * 关键字搜索
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getProdutsByKeyword(Request $request)
    {
        $page = $request->page;
        $start = ($page - 1) * self::$totalList;

        $keyword = $request->keyword;
        $list = Product::select('id', 'product_name', 'product_introduct', 'cover_ico')
            ->where('status', 1)
            ->where('product_name', 'like', '%' . $keyword . '%')
            ->orderBy('id', 'desc')
            ->offset($start)
            ->limit(self::$totalList)
            ->get();

        if (count($list) > 0) {
            foreach ($list as $v) {
                $v->cover_ico = self::$baseImgUrl . '/' . $v->cover_ico;

                $sku = ProductSku::where('product_id', $v->id)->orderBy('member_price', 'asc')->first();
                if ($sku) {
                    $member_price = $sku->member_price;
                    $parameter = $sku->value;
                    $parameterId = $sku->id;
                } else {
                    $member_price = 0.00;
                    $parameter = '无';
                    $parameterId = 0;
                }

                $v->member_price = $member_price;
                $v->parameter = $parameter;
                $v->parameter_id = $parameterId;
            }
        }

        return response()->json(['status' => 1, 'data' => $list]);
    }

    /**
     * 商品详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request)
    {
        $id = $request->id;
        if (!$id) {
            return response()->json(['status' => 0, 'msg' => '参数缺失！']);
        }
        $info = Product::select('id', 'product_name', 'product_introduct', 'sell_num', 'shipping', 'security', 'from', 'pics', 'base_parameter', 'grape_variety', 'wine_taster', 'package')->where('status', 1)->find($id);
        if (!$info) {
            return response()->json(['status' => 0, 'msg' => '该商品不存在！']);
        }

//        $info->grape_variety = array_filter($info->grape_variety);
        $info->cover_ico = self::$baseImgUrl . '/' . $info->cover_ico;
        $urlArr = [];
        if ($info->pics) {
            foreach ($info->pics as $k => $v) {
                $url = self::$baseImgUrl . '/' . $v;
                array_push($urlArr, $url);
            }
        }

        $sku = ProductSku::where('product_id', $id)->orderBy('member_price', 'asc')->first();
        if ($sku) {
            $member_price = $sku->member_price;
            $parameter = $sku->value;
            $parameterId = $sku->id;
        } else {
            $member_price = 0.00;
            $parameter = '无';
            $parameterId = 0;
        }

        $info->member_price = $member_price;
        $info->parameter = $parameter;
        $info->parameter_id = $parameterId;

        $info->pics = $urlArr;
        return response()->json(['status' => 1, 'data' => $info]);
    }

    /**
     * 产品的所有规格
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAllAttrs(Request $request)
    {
        $id = $request->id;
        if (!$id) {
            return response()->json(['status' => 0, 'msg' => '参数缺失！']);
        }
        $skus = ProductSku::select('id', 'value', 'original_price', 'member_price', 'number')->where('product_id', $id)->get();

        $info = [];
        if ($skus) {
            $defaultId = ProductSku::where('product_id', $id)->orderBy('member_price', 'asc')->value('id');
            foreach ($skus as $v) {
                $pInfo = Product::where('id', $id)->first();
                $v->product_name = $pInfo->product_name;
                $v->cover_ico = self::$baseImgUrl . '/' . $pInfo->cover_ico;

                if ($v->id == $defaultId) {
                    $info = $v;
                }
            }
        }

        return response()->json(['status' => 1, 'data' => ['list' => $skus, 'info' => $info]]);
    }

    /**
     * 是否收藏商品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function isCollect(Request $request)
    {
        $id = $request->id;
        $info = Product::where('status', 1)->find($id);
        if (!$info) {
            return response()->json(['status' => 0, 'msg' => '该商品不存在']);
        }

        $uid = $request->uid;
        $collInfo = CollectionProduct::where('uid', $uid)->where('product_id', $id)->first();
        if (!$collInfo) {
            return response()->json(['status' => 1, 'data' => false]);
        } else {
            return response()->json(['status' => 1, 'data' => true]);
        }
    }

    /**
     * 商品收藏
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeCollect(Request $request)
    {
        $id = $request->id;
        $info = Product::where('status', 1)->find($id);
        if (!$info) {
            return response()->json(['status' => 0, 'msg' => '该商品不存在']);
        }

        $uid = $request->uid;
        $collInfo = CollectionProduct::where('uid', $uid)->where('product_id', $id)->first();
        if (!$collInfo) {
            $res = CollectionProduct::create(['uid' => $uid, 'product_id' => $id]);
            if ($res->id > 0) {
                return response()->json(['status' => 1, 'msg' => '收藏成功！']);
            } else {
                return response()->json(['status' => 0, 'msg' => '收藏失败！']);
            }

        } else {
            $res = CollectionProduct::destroy($collInfo->id);
            if ($res) {
                return response()->json(['status' => 1, 'msg' => '取消收藏成功！']);
            } else {
                return response()->json(['status' => 1, 'msg' => '取消收藏失败！']);
            }
        }
    }

    /**
     * 商品收藏
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function shopCollect(Request $request)
    {
        $page = $request->page;
        $start = ($page - 1) * self::$totalList;

        $uid = $request->uid;
        $collInfos = DB::table('collection_product')->join('products', 'collection_product.product_id', '=', 'products.id')
            ->select('collection_product.id', 'collection_product.product_id', 'products.product_name', 'products.cover_ico')
            ->where('collection_product.uid', $uid)
            ->where('products.status', 1)
            ->orderBy('id', 'desc')
            ->offset($start)
            ->limit(self::$totalList)
            ->get();

        $totalCount = DB::table('collection_product')->join('products', 'collection_product.product_id', '=', 'products.id')
            ->where('collection_product.uid', $uid)
            ->where('products.status', 1)
            ->count();

        if ($collInfos) {
            foreach ($collInfos as $v) {
                $v->cover_ico = self::$baseImgUrl . '/' . $v->cover_ico;

                $sku = ProductSku::where('product_id', $v->product_id)->where('number', '>=', 1)->orderBy('member_price', 'asc')->first();
                if ($sku) {
                    $member_price = $sku->member_price;
                    $parameter = $sku->value;
                    $parameterId = $sku->id;
                } else {
                    $member_price = 0.00;
                    $parameter = '无';
                    $parameterId = 0;
                }

                $v->price = $member_price;
                $v->parameter = $parameter;
                $v->parameter_id = $parameterId;
            }
        }

        return response()->json(['status' => 1, 'data' => ['data' => $collInfos, 'totalCount' => $totalCount]]);
    }

    /**
     * 删除收藏
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delCollect(Request $request)
    {
        $uid = $request->uid;
        $ids = $request->ids;

        $idsArr = array_unique(explode(',', $ids));

        $res = CollectionProduct::where('uid', $uid)->whereIn('id', $idsArr)->delete();
        if ($res) {
            return response()->json(['status' => 1, 'msg' => '删除成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '删除失败']);
        }

    }

    /**
     * 商品浏览记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function shopBrowser(Request $request)
    {
        $page = $request->page;
        $start = ($page - 1) * self::$totalList;

        $uid = $request->uid;
        $browInfos = DB::table('browser_product')->join('products', 'browser_product.product_id', '=', 'products.id')
            ->select('browser_product.id', 'browser_product.product_id', 'products.product_name', 'products.cover_ico')
            ->where('browser_product.uid', $uid)
            ->where('products.status', 1)
            ->orderBy('id', 'desc')
            ->offset($start)
            ->limit(self::$totalList)
            ->get();

        $totalCount = DB::table('browser_product')->join('products', 'browser_product.product_id', '=', 'products.id')
            ->where('browser_product.uid', $uid)
            ->count();
        if ($browInfos) {
            foreach ($browInfos as $v) {
                $v->cover_ico = self::$baseImgUrl . '/' . $v->cover_ico;

                $sku = ProductSku::where('product_id', $v->product_id)->where('number', '>=', 1)->orderBy('member_price', 'asc')->first();
                if ($sku) {
                    $member_price = $sku->member_price;
                    $parameter = $sku->value;
                    $parameterId = $sku->id;
                } else {
                    $member_price = 0.00;
                    $parameter = '无';
                    $parameterId = 0;
                }

                $v->price = $member_price;
                $v->parameter = $parameter;
                $v->parameter_id = $parameterId;
            }
        }

        return response()->json(['status' => 1, 'data' => ['data' => $browInfos, 'totalCount' => $totalCount]]);
    }

    /**
     * 添加商品浏览记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addShopBrowser(Request $request)
    {
        $id = $request->id;
        $info = Product::where('status', 1)->find($id);
        if (!$info) {
            return response()->json(['status' => 0, 'msg' => '该商品不存在']);
        }

        $uid = $request->uid;
        $collInfo = BrowserProduct::where('uid', $uid)->where('product_id', $id)->first();
        if ($collInfo) {
            return response()->json(['status' => 1, 'msg' => '已加入浏览记录！']);
        }
        BrowserProduct::create(['uid' => $uid, 'product_id' => $id]);
        return response()->json(['status' => 1, 'msg' => '加入浏览记录！']);
    }

    /**
     * 删除商品浏览记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delBrowser(Request $request)
    {
        $uid = $request->uid;
        $ids = $request->ids;

        $idsArr = array_unique(explode(',', $ids));

        $res = BrowserProduct::where('uid', $uid)->whereIn('id', $idsArr)->delete();
        if ($res) {
            return response()->json(['status' => 1, 'msg' => '删除成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '删除失败']);
        }

    }

    /**
     * 加入购物车
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addCart(Request $request)
    {
        $parameterId = $request->parameter_id;
        if ($parameterId <= 0) {
            return response()->json(['status' => 0, 'msg' => '必须选择商品规格！']);
        }
        $id = ProductSku::where('id', $parameterId)->value('product_id');
        $info = Product::where('status', 1)->find($id);
        if (!$info) {
            return response()->json(['status' => 0, 'msg' => '该商品不存在']);
        }

        $number = $request->number > 0 ? $request->number : 1;

        $hasNumber = ProductSku::where('id', $parameterId)->value('number');
        if ($hasNumber < $number) {
            return response()->json(['status' => 0, 'msg' => '商品余量不足！']);
        }

        $uid = $request->uid;

        $collInfo = ProductCart::where('uid', $uid)->where('product_id', $id)->where('parameter_id', $parameterId)->first();
        if ($collInfo) {
            return response()->json(['status' => 0, 'msg' => '已加入购物车！']);
        }
        $res = ProductCart::create(['uid' => $uid, 'product_id' => $id, 'parameter_id' => $parameterId, 'number' => $number]);
        if ($res->id > 0) {
            return response()->json(['status' => 1, 'msg' => '成功加入购物车！']);
        } else {
            return response()->json(['status' => 0, 'msg' => '加入购物车失败！']);
        }
    }

    /**
     * 我的购物车
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function cartList(Request $request)
    {
        $uid = $request->uid;
        $carts = ProductCart::where('uid', $uid)->orderBy('id', 'desc')->get();
        if ($carts) {
            foreach ($carts as $v) {
                $pInfo = Product::where('id', $v->product_id)->select('member_price', 'product_name', 'cover_ico', 'num')->first();

                $v->product_name = $pInfo->product_name;
                $v->cover_ico = self::$baseImgUrl . '/' . $pInfo->cover_ico;

                $parameterInfo = ProductSku::where('id', $v->parameter_id)->first();
                $v->parameter = $parameterInfo->value;
                $v->price = $parameterInfo->member_price;
            }
        }

        return response()->json(['status' => 1, 'data' => $carts]);
    }

    /**
     * 删除购物车商品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delCart(Request $request)
    {
        $cid = $request->id;
        $cinfo = ProductCart::find($cid);
        if (!$cinfo) {
            return response()->json(['status' => 0, 'msg' => '购物车中不存在该商品']);
        }

        $res = ProductCart::destroy($cinfo->id);
        if ($res) {
            return response()->json(['status' => 1, 'msg' => '删除成功！']);
        } else {
            return response()->json(['status' => 0, 'msg' => '删除失败！']);
        }

    }

    /**
     * 清空购物车
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function clearCart(Request $request)
    {
        $idsStr = $request->ids;
        if (!$idsStr) {
            return response()->json(['status' => 0, 'msg' => '参数缺失']);
        }
        $idsArr = json_decode($idsStr, true);
        $uid = $request->uid;
        $res = ProductCart::where('uid', $uid)->whereIn('id', $idsArr)->delete();
        if ($res) {
            return response()->json(['status' => 1, 'msg' => '删除成功']);
        } else {
            return response()->json(['status' => 0, 'msg' => '删除失败']);
        }
    }

    /**
     * 去下单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function goOrder(Request $request)
    {
        $tag = $request->tag;
        $oInfo = ProductOrder::select("order_number", "total", "transfee", "all", "create_time", 'addressid')->where('order_number', $tag)->first();
        if (!$oInfo) {
            return response()->json(['status' => 0, 'msg' => '该订单不存在！']);
        }
        if ($oInfo->status >= 1) {
            return response()->json(['status' => 0, 'msg' => '该订单已支付！']);
        }

        return response()->json(['status' => 1, 'msg' => '可以继续支付！']);
    }

    /**
     * 商品结算
     */
    public function order(Request $request)
    {
        $data = $request->data;
        if (!$data) {
            return response()->json(['status' => 0, 'msg' => '参数缺失！']);
        }

        $dataArr = json_decode($data, true);
        if (count($dataArr) <= 0) {
            return response()->json(['status' => 0, 'msg' => '请至少选择一个商品！']);
        }

        $uid = $request->uid;
        $tag = $this->create_order($uid);

        $list = [];

        foreach ($dataArr as $k => $v) {
            if ($v['parameter_id'] <= 0) {
                return response()->json(['status' => 0, 'msg' => '商品规格缺失！']);
            }
            $pInfo = ProductSku::where('id', $v['parameter_id'])->select('product_id', 'number', 'member_price')->first();

            if ($pInfo['number'] < $v['number']) {
                return response()->json(['status' => 0, 'msg' => '商品余量不足！']);
            }

            $price = $pInfo->member_price;
            $orderNumber = $this->create_order($uid);
            $item = [
                'order_numbero' => $tag,
                'order_number' => $orderNumber,
                'product_id' => $pInfo['product_id'],
//                'goodname' => $shop['goods_name'],
                'uid' => $uid,
                'parameter_id' => $v['parameter_id'],
                'price' => $price,
                'num' => $v['number'],
                'total' => $price * $v['number'],
                'create_time' => time(),
                'status' => 0,
            ];
            array_push($list, $item);
        }

        $res = DB::table('product_list')->insert($list);
        if ($res) {
            return response()->json(['status' => 1, 'msg' => '生成商品清单！', 'data' => $tag]);
        } else {
            return response()->json(['status' => 0, 'msg' => '操作失败！']);
        }
    }

    /**
     * 再次购买
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function payAgain(Request $request)
    {
        $uid = $request->uid;
        $otag = $request->tag;
        $olist = ProductList::where('order_numbero', $otag)->get();

        $tag = $this->create_order($uid);
        $list = [];
        foreach ($olist as $k => $v) {
            $pInfo = Product::where('id', $v['product_id'])->select('num', 'member_price', 'category_id')->first();

            if ($pInfo['num'] < $v['num']) {
                return response()->json(['status' => 0, 'msg' => '商品余量不足！']);
            }

            $orderNumber = $this->create_order($uid);
            $item = [
                'order_numbero' => $tag,
                'order_number' => $orderNumber,
                'product_id' => $v['product_id'],
//                'goodname' => $shop['goods_name'],
                'uid' => $uid,
//                'parameters' => $parameters_arr[$k],
                'price' => $v['price'],
                'num' => $v['num'],
                'total' => $v['price'] * $v['num'],
                'create_time' => time(),
                'status' => 0,
            ];
            array_push($list, $item);
        }

        $res = DB::table('product_list')->insert($list);
        if ($res) {
            return response()->json(['status' => 1, 'msg' => '生成商品清单！', 'data' => $tag]);
        } else {
            return response()->json(['status' => 0, 'msg' => '操作失败！']);
        }
    }

    /**
     * 获取商品清单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOrder(Request $request)
    {
        $tag = $request->tag;
        $lists = ProductList::select('product_id', 'parameter_id', 'price', 'num', 'total')->where("order_numbero", $tag)->orderBy('id', 'desc')->get();

        $total = $num = $transfee = 0;

        foreach ($lists as $val) {
            $pInfo = Product::where('id', $val['product_id'])->select('product_name', 'cover_ico', 'product_introduct', 'transfee')->first();
            $val->product_name = $pInfo->product_name;
            $val->cover_ico = self::$baseImgUrl . '/' . $pInfo->cover_ico;
            $val->product_introduct = $pInfo->product_introduct;

            $total += $val->total;
            $num += $val->num;        //商品数量
            $transfee += $pInfo->transfee * $val->num;

            $parameter = ProductSku::where('id', $val->parameter_id)->value('value');
            $val->parameter = $parameter;
        }

        $data = [
            'list' => $lists,
            'transfee' => $transfee,
            'num' => $num,
            'total' => round($total, 2),
        ];

        return response()->json(['status' => 1, 'msg' => '商品清单！', 'data' => $data]);
    }

    /**
     * 提交订单
     */
    public function createOrder(Request $request)
    {
        $uid = $request->uid;
        $tag = $request->tag;//标识号

        $addressid = $request->addressid;
        if ($addressid <= 0) {
            return response()->json(['status' => 600, 'msg' => '必须选择一个收货地址！']);
        }

        $pList = ProductList::where('order_numbero', $tag)->get();
        if (!$pList) {
            return response()->json(['status' => 500, 'msg' => '请先选购商品！']);
        }

        $oInfo = ProductOrder::where('order_number', $tag)->first();
        if ($oInfo) {
            if ($oInfo->status >= 1) {
                return response()->json(['status' => 0, 'msg' => '该订单已支付！']);
            }
            ProductOrder::where('id', $oInfo->id)->update(['create_time' => time(), 'addressid' => $addressid]);
            return response()->json(['status' => 1, 'msg' => '去支付！']);
        }

        //清空购物车
        ProductCart::where('uid', $uid)->delete();

        $nums = $total = 0;
        foreach ($pList as $v) {
            $nums += $v['num'];
            $total += $v['total'];
        }

        $transfee = 0;
        $all = $total + $transfee;
        $message = $request->message;
        $invoiceId = $request->invoiceid;
        $odata = [
            'uid' => $uid,
            'order_number' => $tag,
            'message' => $message,
            'addressid' => $addressid,
            'invoice_id' => $invoiceId,
            'total' => $total,
            'transfee' => $transfee,
            'all' => $all,
            'status' => 0,
            'create_time' => time(),
        ];

        //根据订单id保存对应的费用数据
        DB::beginTransaction();
        $oInfo = ProductOrder::create($odata);
        $res = ProductList::where('order_numbero', $tag)->update(['order_id' => $oInfo->id]);

        if ($res) {
            DB::commit();
            return response()->json(['status' => 1, 'msg' => '订单创建成功！']);
        } else {
            DB::rollback();
            return response()->json(['status' => 0, 'msg' => '订单创建失败！']);
        }
    }

    /**
     * 去支付订单
     * @param Request $request
     * @return bool|\Illuminate\Http\JsonResponse|mixed|\SimpleXMLElement|string|\构建好的、签名后的最终跳转URL（GET）或String形式的form（POST）
     */
    public function goPay(Request $request)
    {
        $tag = $request->tag;
        $oInfo = ProductOrder::where('order_number', $tag)->first();
        if (!$oInfo) {
            return response()->json(['status' => 0, 'msg' => '该订单不存在！']);
        }
        if ($oInfo->status >= 1) {
            return response()->json(['status' => 0, 'msg' => '该订单已支付！']);
        }

        $ip = $request->getClientIp();

        $data = [
            "body" => '酒书',
            "out_trade_no" => $oInfo->order_number,
            //                "out_trade_no" => time(),
            "client_ip" => $ip,
            "money" => $oInfo->all,
//            "money" => 0.01
        ];

        $payMent = new PaymentController();
        $res = $payMent->wx_pay($data);

        if ($res['status'] == 0) {
            return response()->json(['status' => 0, 'msg' => $res['msg']]);
        } else {
            return response()->json($res);
        }
    }

    /**
     * 订单列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function orders(Request $request)
    {
        $totalList = 10;
        $page = $request->page;
        $start = ($page - 1) * $totalList;

        $uid = $request->uid;

        $status = $request->status;
        $orders = ProductOrder::with('product_list')
            ->select('id', 'status', 'total', 'create_time', 'order_number')
            ->where('uid', $uid)
            ->where(function ($query) use ($status) {
                if ($status > -1) {
                    $query->where('status', $status);
                } else {
                    $query->where('status', '>=', 0);
                }
            })
            ->orderBy('id', 'desc')
            ->skip($start)
            ->take($totalList)
            ->get()->toArray();

        if ($orders) {
            foreach ($orders as &$v) {
                $lists = $v['product_list'];
                $totalNum = 0;
                if (count($lists) > 0) {
                    foreach ($lists as &$vv) {
                        $pInfo = Product::where('id', $vv['product_id'])->select('product_name', 'cover_ico')->first();
                        $vv['product_name'] = $pInfo['product_name'];
                        $vv['parameter'] = ProductSku::where('id', $vv['parameter_id'])->value('value');
                        $vv['cover_ico'] = self::$baseImgUrl . '/' . $pInfo['cover_ico'];
                        $totalNum += $vv['num'];
                    }
                }
                $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                $v['total_num'] = $totalNum;
                $v['product_list'] = $lists;
            }
        }

        $totalCount = ProductOrder::where('uid', $uid)
            ->where(function ($query) use ($status) {
                if ($status > -1) {
                    $query->where('status', $status);
                }
            })
            ->count();

        return response()->json(['status' => 1, 'data' => ['list' => $orders, 'totalCount' => $totalCount]]);
    }

    /**
     * 取消订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function cancleOrder(Request $request)
    {
        $id = $request->id;
        $uid = $request->uid;
        $oInfo = ProductOrder::where('id', $id)->where('uid', $uid)->first();
        if (!$oInfo) {
            return response()->json(['status' => 0, 'msg' => '非法操作！']);
        }
        if ($oInfo->status != 0) {
            return response()->json(['status' => 0, 'msg' => '该订单不可取消！']);
        }

        DB::beginTransaction();
        try {
            ProductOrder::where('id', $id)->delete();
            ProductList::where('order_id', $id)->delete();

            DB::commit();
            return response()->json(['status' => 1, 'msg' => '取消成功！']);
        } catch (QueryException $exception) {
            DB::rollback();
            return response()->json(['status' => 0, 'msg' => '取消失败！']);
        }
    }

    /**
     * 删除订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delOrder(Request $request)
    {
        $id = $request->id;
        $oInfo = ProductOrder::where('id', $id)->first();
        if (!$oInfo) {
            return response()->json(['status' => 0, 'msg' => '非法操作！']);
        }
        if ($oInfo->status != 20) {
            return response()->json(['status' => 0, 'msg' => '该订单不可删除！']);
        }

        DB::beginTransaction();
        try {
            ProductOrder::where('id', $id)->update(['status' => -2]);
            ProductList::where('order_id', $id)->update(['status' => -2]);

            DB::commit();
            return response()->json(['status' => 1, 'msg' => '删除成功！']);
        } catch (QueryException $exception) {
            DB::rollback();
            return response()->json(['status' => 0, 'msg' => '删除失败！']);
        }
    }

    /**
     * 确认订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function confirmOrder(Request $request)
    {
        $uid = $request->uid;
        $id = $request->id;
        $oinfo = ProductOrder::where('uid', $uid)->where('id', $id)->first();
        if (!$oinfo) {
            return response()->json(['status' => 0, 'msg' => '该订单不存在！']);
        }
        if ($oinfo->status != 10) {
            return response()->json(['status' => 0, 'msg' => '该订单不可确认！']);
        }

        $data = [
            'status' => 20,
            'finish_time' => time()
        ];
        $res = ProductOrder::where('id', $id)->update($data);

        if (!$res) {
            return response()->json(['status' => 0, 'msg' => '签单失败！']);
        }

        ProductList::where('order_id', $id)->update($data);

        return response()->json(['status' => 1, 'msg' => '签单成功！']);
    }

    /**
     * 获取所有收货地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAllAddress(Request $request)
    {
        $uid = $request->uid;
        $addresses = ShippingAddress::select('id', 'mobile', 'area', 'address', 'realname', 'status')->where('uid', $uid)->orderBy('id', 'desc')->get();
        if ($addresses) {
            foreach ($addresses as $v) {
                $v->area_id = $v->area;
                $v->area = CollArea::getAreaAddress($v->area);
                $v->area_arr = CollArea::getAreaAddressThree($v->area_id);
            }
        }

        return response()->json(['status' => 1, 'data' => $addresses]);
    }

    /**
     * 默认收货地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDefaultAddress(Request $request)
    {
        $uid = $request->uid;
        $default = ShippingAddress::select('id', 'mobile', 'realname', 'area', 'address')->where('uid', $uid)->where('status', 1)->first();

        if ($default) {
            $default->area = CollArea::getAreaAddress($default->area);
        }

        return response()->json(['status' => 1, 'msg' => '默认收货地址！', 'data' => $default]);
    }

    /**
     * 地址详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addressInfo(Request $request)
    {
        $uid = $request->uid;
        $id = $request->id;
        $addressInfo = ShippingAddress::select('id', 'mobile', 'realname', 'area', 'address', 'status')->where('uid', $uid)->where('id', $id)->first();

        if (!$addressInfo) {
            return response()->json(['status' => 0, 'msg' => '该地址不存在！']);
        }

        $addressInfo->area_arr = CollArea::getAreaAddressThree($addressInfo->area);

        return response()->json(['status' => 1, 'data' => $addressInfo]);
    }

    /**
     * 添加或编辑地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function editAddress(Request $request)
    {
        $input = $request->input();
        if (isset($input['default']) && $input['default'] == "true") {
            ShippingAddress::where('uid', $input['uid'])->update(['status' => 0]);
            $input['status'] = 1;
        } else {
            $input['status'] = 0;
        }

        $uid = $input['uid'];
        $num = ShippingAddress::where('uid', $uid)->count();
        if ($num <= 0) {
            $input['status'] = 1;
        }

        if (isset($input['id']) && $input['id'] > 0) {
            $id = $input['id'];
        } else {
            $id = 0;
        }

        $data = [
            'uid' => $uid,
            'realname' => $input['realname'],
            'mobile' => $input['mobile'],
            'area' => $input['area'],
            'address' => $input['address'],
            'status' => $input['status']
        ];

        if ($id <= 0) {
            $data['create_time'] = date('Y-m-d H:i:s', time());
            $res = ShippingAddress::create($data);
            $msg = '添加';
        } else {
            $res = ShippingAddress::where('id', $id)->update($data);
            $msg = '更新';
        }

        if ($res) {
            return response()->json(['status' => 1, 'msg' => $msg . '成功！']);
        } else {
            return response()->json(['status' => 0, 'msg' => $msg . '失败！']);
        }
    }
}
